home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / system-config-printer / authconn.py < prev    next >
Encoding:
Python Source  |  2009-05-05  |  16.1 KB  |  443 lines

  1. #!/usr/bin/env python
  2.  
  3. ## Copyright (C) 2007, 2008, 2009 Tim Waugh <twaugh@redhat.com>
  4. ## Copyright (C) 2007, 2008, 2009 Red Hat, Inc.
  5.  
  6. ## This program is free software; you can redistribute it and/or modify
  7. ## it under the terms of the GNU General Public License as published by
  8. ## the Free Software Foundation; either version 2 of the License, or
  9. ## (at your option) any later version.
  10.  
  11. ## This program is distributed in the hope that it will be useful,
  12. ## but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. ## GNU General Public License for more details.
  15.  
  16. ## You should have received a copy of the GNU General Public License
  17. ## along with this program; if not, write to the Free Software
  18. ## Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  19.  
  20. import threading
  21. import cups
  22. import cupspk
  23. import gobject
  24. import gtk
  25. from errordialogs import *
  26. from debug import *
  27.  
  28. _ = lambda x: x
  29. N_ = lambda x: x
  30. def set_gettext_function (fn):
  31.     global _
  32.     _ = fn
  33.  
  34. class AuthDialog(gtk.Dialog):
  35.     AUTH_FIELD={'username': N_("Username:"),
  36.                 'password': N_("Password:"),
  37.                 'domain': N_("Domain:")}
  38.  
  39.     def __init__ (self, title=None, parent=None,
  40.                   flags=gtk.DIALOG_MODAL | gtk.DIALOG_NO_SEPARATOR,
  41.                   buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
  42.                            gtk.STOCK_OK, gtk.RESPONSE_OK),
  43.                   auth_info_required=['username', 'password'],
  44.                   allow_remember=False):
  45.         if title == None:
  46.             title = _("Authentication")
  47.         gtk.Dialog.__init__ (self, title, parent, flags, buttons)
  48.         self.auth_info_required = auth_info_required
  49.         self.set_default_response (gtk.RESPONSE_OK)
  50.         self.set_border_width (6)
  51.         self.set_resizable (False)
  52.         hbox = gtk.HBox (False, 12)
  53.         hbox.set_border_width (6)
  54.         image = gtk.Image ()
  55.         image.set_from_stock (gtk.STOCK_DIALOG_AUTHENTICATION,
  56.                               gtk.ICON_SIZE_DIALOG)
  57.         image.set_alignment (0.0, 0.0)
  58.         hbox.pack_start (image, False, False, 0)
  59.         vbox = gtk.VBox (False, 12)
  60.         self.prompt_label = gtk.Label ()
  61.         vbox.pack_start (self.prompt_label, False, False, 0)
  62.  
  63.         num_fields = len (auth_info_required)
  64.         table = gtk.Table (num_fields, 2)
  65.         table.set_row_spacings (6)
  66.         table.set_col_spacings (6)
  67.  
  68.         self.field_entry = []
  69.         for i in range (num_fields):
  70.             field = auth_info_required[i]
  71.             label = gtk.Label (_(self.AUTH_FIELD.get (field, field)))
  72.             label.set_alignment (0, 0.5)
  73.             table.attach (label, 0, 1, i, i + 1)
  74.             entry = gtk.Entry ()
  75.             entry.set_visibility (field != 'password')
  76.             table.attach (entry, 1, 2, i, i + 1, 0, 0)
  77.             self.field_entry.append (entry)
  78.  
  79.         self.field_entry[num_fields - 1].set_activates_default (True)
  80.         vbox.pack_start (table, False, False, 0)
  81.         hbox.pack_start (vbox, False, False, 0)
  82.         self.vbox.pack_start (hbox)
  83.  
  84.         if allow_remember:
  85.             cb = gtk.CheckButton (_("Remember password"))
  86.             cb.set_active (False)
  87.             vbox.pack_start (cb)
  88.             self.remember_checkbox = cb
  89.  
  90.         self.vbox.show_all ()
  91.  
  92.     def set_prompt (self, prompt):
  93.         self.prompt_label.set_markup ('<span weight="bold" size="larger">' +
  94.                                       prompt + '</span>')
  95.         self.prompt_label.set_use_markup (True)
  96.         self.prompt_label.set_alignment (0, 0)
  97.         self.prompt_label.set_line_wrap (True)
  98.  
  99.     def set_auth_info (self, auth_info):
  100.         for i in range (len (self.field_entry)):
  101.             self.field_entry[i].set_text (auth_info[i])
  102.  
  103.     def get_auth_info (self):
  104.         return map (lambda x: x.get_text (), self.field_entry)
  105.  
  106.     def get_remember_password (self):
  107.         try:
  108.             return self.remember_checkbox.get_active ()
  109.         except AttributeError:
  110.             return False
  111.  
  112.     def field_grab_focus (self, field):
  113.         i = self.auth_info_required.index (field)
  114.         self.field_entry[i].grab_focus ()
  115.  
  116. class Connection:
  117.     def __init__ (self, parent=None, try_as_root=True, lock=False,
  118.                   host=None, port=None, encryption=None):
  119.         if host != None:
  120.             cups.setServer (host)
  121.         if port != None:
  122.             cups.setPort (port)
  123.         if encryption != None:
  124.             cups.setEncryption (encryption)
  125.  
  126.         self._use_password = ''
  127.         self._parent = parent
  128.         self._try_as_root = try_as_root
  129.         self._use_user = cups.getUser ()
  130.         self._server = cups.getServer ()
  131.         self._port = cups.getPort()
  132.         self._encryption = cups.getEncryption ()
  133.         self._connect ()
  134.         self._prompt_allowed = True
  135.         self._operation_stack = []
  136.         self._lock = lock
  137.         self._gui_event = threading.Event ()
  138.  
  139.     def _begin_operation (self, operation):
  140.         self._operation_stack.append (operation)
  141.  
  142.     def _end_operation (self):
  143.         self._operation_stack.pop ()
  144.  
  145.     def _get_prompt_allowed (self, ):
  146.         return self._prompt_allowed
  147.  
  148.     def _set_prompt_allowed (self, allowed):
  149.         self._prompt_allowed = allowed
  150.  
  151.     def _set_lock (self, whether):
  152.         self._lock = whether
  153.  
  154.     def _connect (self):
  155.         cups.setUser (self._use_user)
  156.  
  157.         self._use_pk = self._server[0] == '/' or self._server == 'localhost'
  158.         if self._use_pk:
  159.             create_object = cupspk.Connection
  160.         else:
  161.             create_object = cups.Connection
  162.  
  163.         self._connection = create_object (host=self._server,
  164.                                             port=self._port,
  165.                                             encryption=self._encryption)
  166.  
  167.         if self._use_pk:
  168.             self._connection.set_parent(self._parent)
  169.  
  170.         self._user = self._use_user
  171.         debugprint ("Connected as user %s" % self._user)
  172.         methodtype_lambda = type (self._connection.getPrinters)
  173.         methodtype_real = type (self._connection.addPrinter)
  174.         for fname in dir (self._connection):
  175.             if fname[0] == '_':
  176.                 continue
  177.             fn = getattr (self._connection, fname)
  178.             if not type (fn) in [methodtype_lambda, methodtype_real]:
  179.                 continue
  180.             setattr (self, fname, self._make_binding (fname, fn))
  181.  
  182.     def _make_binding (self, fname, fn):
  183.         return lambda *args, **kwds: self._authloop (fname, fn, *args, **kwds)
  184.  
  185.     def _authloop (self, fname, fn, *args, **kwds):
  186.         self._passes = 0
  187.         c = self._connection
  188.         retry = False
  189.         while retry or self._perform_authentication () != 0:
  190.             if c != self._connection:
  191.                 # We have reconnected.
  192.                 fn = getattr (self._connection, fname)
  193.                 c = self._connection
  194.  
  195.             cups.setUser (self._use_user)
  196.  
  197.             try:
  198.                 result = fn.__call__ (*args, **kwds)
  199.  
  200.                 if fname == 'adminGetServerSettings':
  201.                     # Special case for a rubbish bit of API.
  202.                     if result == {}:
  203.                         # Authentication failed, but we aren't told that.
  204.                         raise cups.IPPError (cups.IPP_NOT_AUTHORIZED, '')
  205.                 break
  206.             except cups.IPPError, (e, m):
  207.                 if self._use_pk and m == 'pkcancel':
  208.                     title = 'Unauthorized request (%s)' % fname
  209.                     text = 'You are not authorized for the requested action'
  210.                     show_info_dialog (title, text, None)
  211.                     raise cups.IPPError (0, _("Operation canceled"))
  212.                 if not self._cancel and (e == cups.IPP_NOT_AUTHORIZED or
  213.                                          e == cups.IPP_FORBIDDEN):
  214.                     self._failed (e == cups.IPP_FORBIDDEN)
  215.                 elif not self._cancel and e == cups.IPP_SERVICE_UNAVAILABLE:
  216.                     if self._lock:
  217.                         self._gui_event.clear ()
  218.                         gobject.timeout_add (1, self._ask_retry_server_error, m)
  219.                         self._gui_event.wait ()
  220.                     else:
  221.                         self._ask_retry_server_error (m)
  222.  
  223.                     if self._retry_response == gtk.RESPONSE_OK:
  224.                         debugprint ("retrying operation...")
  225.                         retry = True
  226.                         self._passes -= 1
  227.                     else:
  228.                         self._cancel = True
  229.                         raise
  230.                 else:
  231.                     if self._cancel and not self._cannot_auth:
  232.                         raise cups.IPPError (0, _("Operation canceled"))
  233.  
  234.                     raise
  235.             except cups.HTTPError, (s,):
  236.                 if not self._cancel and (s == cups.HTTP_UNAUTHORIZED or
  237.                                          s == cups.HTTP_FORBIDDEN):
  238.                     self._failed (s == cups.HTTP_FORBIDDEN)
  239.                 else:
  240.                     raise
  241.  
  242.         return result
  243.  
  244.     def _ask_retry_server_error (self, message):
  245.         if self._lock:
  246.             gtk.gdk.threads_enter ()
  247.  
  248.         d = gtk.MessageDialog (self._parent,
  249.                                gtk.DIALOG_MODAL |
  250.                                gtk.DIALOG_DESTROY_WITH_PARENT,
  251.                                gtk.MESSAGE_ERROR,
  252.                                gtk.BUTTONS_NONE,
  253.                                _("CUPS server error (%s)") %
  254.                                self._operation_stack[0])
  255.         d.format_secondary_text (_("There was an error during the "
  256.                                    "CUPS operation: '%s'." % message))
  257.         d.add_buttons (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
  258.                        _("Retry"), gtk.RESPONSE_OK)
  259.         d.set_default_response (gtk.RESPONSE_OK)
  260.         if self._lock:
  261.             d.connect ("response", self._on_retry_server_error_response)
  262.             gtk.gdk.threads_leave ()
  263.         else:
  264.             self._retry_response = d.run ()
  265.             d.destroy ()
  266.  
  267.     def _on_retry_server_error_response (self, dialog, response):
  268.         self._retry_response = response
  269.         dialog.destroy ()
  270.         self._gui_event.set ()
  271.  
  272.     def _failed (self, forbidden=False):
  273.         self._has_failed = True
  274.         self._forbidden = forbidden
  275.  
  276.     def _password_callback (self, prompt):
  277.         debugprint ("Got password callback")
  278.         if self._cancel or self._auth_called:
  279.             return ''
  280.  
  281.         self._auth_called = True
  282.         self._prompt = prompt
  283.         return self._use_password
  284.  
  285.     def _perform_authentication (self):
  286.         self._passes += 1
  287.  
  288.         debugprint ("Authentication pass: %d" % self._passes)
  289.         if self._passes == 1:
  290.             # Haven't yet tried the operation.  Set the password
  291.             # callback and return > 0 so we try it for the first time.
  292.             self._has_failed = False
  293.             self._forbidden = False
  294.             self._auth_called = False
  295.             self._cancel = False
  296.             self._cannot_auth = False
  297.             self._dialog_shown = False
  298.             cups.setPasswordCB (self._password_callback)
  299.             debugprint ("Authentication: password callback set")
  300.             return 1
  301.  
  302.         debugprint ("Forbidden: %s" % self._forbidden)
  303.         if not self._has_failed:
  304.             # Tried the operation and it worked.  Return 0 to signal to
  305.             # break out of the loop.
  306.             debugprint ("Authentication: Operation successful")
  307.             return 0
  308.  
  309.         # Reset failure flag.
  310.         self._has_failed = False
  311.  
  312.         if self._passes >= 2:
  313.             # Tried the operation without a password and it failed.
  314.             if (self._try_as_root and
  315.                 self._user != 'root' and
  316.                 (self._server[0] == '/' or self._forbidden)):
  317.                 # This is a UNIX domain socket connection so we should
  318.                 # not have needed a password (or it is not a UDS but
  319.                 # we got an HTTP_FORBIDDEN response), and so the
  320.                 # operation must not be something that the current
  321.                 # user is authorised to do.  They need to try as root,
  322.                 # and supply the password.  However, to get the right
  323.                 # prompt, we need to try as root but with no password
  324.                 # first.
  325.                 debugprint ("Authentication: Try as root")
  326.                 self._use_user = 'root'
  327.                 self._auth_called = False
  328.                 self._connect ()
  329.                 return 1
  330.  
  331.         if not self._prompt_allowed:
  332.             debugprint ("Authentication: prompting not allowed")
  333.             self._cancel = True
  334.             return 1
  335.  
  336.         if not self._auth_called:
  337.             # We aren't even getting a chance to supply credentials.
  338.             debugprint ("Authentication: giving up")
  339.             self._cancel = True
  340.             self._cannot_auth = True
  341.             return 1
  342.  
  343.         # Reset the flag indicating whether we were given an auth callback.
  344.         self._auth_called = False
  345.  
  346.         # If we're previously prompted, explain why we're prompting again.
  347.         if self._dialog_shown:
  348.             if self._lock:
  349.                 self._gui_event.clear ()
  350.                 gobject.timeout_add (1, self._show_not_authorized_dialog)
  351.                 self._gui_event.wait ()
  352.             else:
  353.                 self._show_not_authorized_dialog ()
  354.  
  355.         if self._lock:
  356.             self._gui_event.clear ()
  357.             gobject.timeout_add (1, self._perform_authentication_with_dialog)
  358.             self._gui_event.wait ()
  359.         else:
  360.             self._perform_authentication_with_dialog ()
  361.  
  362.         if self._cancel:
  363.             debugprint ("cancelled")
  364.             return -1
  365.  
  366.         cups.setUser (self._use_user)
  367.         debugprint ("Authentication: Reconnect")
  368.         self._connect ()
  369.         return 1
  370.  
  371.     def _show_not_authorized_dialog (self):
  372.         if self._lock:
  373.             gtk.gdk.threads_enter ()
  374.         d = gtk.MessageDialog (self._parent,
  375.                                gtk.DIALOG_MODAL |
  376.                                gtk.DIALOG_DESTROY_WITH_PARENT,
  377.                                gtk.MESSAGE_ERROR,
  378.                                gtk.BUTTONS_CLOSE)
  379.         d.set_title (_("Not authorized"))
  380.         d.set_markup ('<span weight="bold" size="larger">' +
  381.                       _("Not authorized") + '</span>\n\n' +
  382.                       _("The password may be incorrect."))
  383.         if self._lock:
  384.             d.connect ("response", self._on_not_authorized_dialog_response)
  385.             gtk.gdk.threads_leave ()
  386.         else:
  387.             d.run ()
  388.             d.destroy ()
  389.  
  390.     def _on_not_authorized_dialog_response (self, dialog, response):
  391.         self._gui_event.set ()
  392.         dialog.destroy ()
  393.  
  394.     def _perform_authentication_with_dialog (self):
  395.         if self._lock:
  396.             gtk.gdk.threads_enter ()
  397.  
  398.         # Prompt.
  399.         if len (self._operation_stack) > 0:
  400.             d = AuthDialog (title=_("Authentication (%s)") %
  401.                             self._operation_stack[0],
  402.                             parent=self._parent)
  403.         else:
  404.             d = AuthDialog (parent=self._parent)
  405.  
  406.         d.set_prompt (self._prompt)
  407.         d.set_auth_info ([self._use_user, ''])
  408.         d.field_grab_focus ('password')
  409.         d.set_keep_above (True)
  410.         d.show_all ()
  411.         d.show_now ()
  412.         self._dialog_shown = True
  413.         if self._lock:
  414.             d.connect ("response", self._on_authentication_response)
  415.             gtk.gdk.threads_leave ()
  416.         else:
  417.             response = d.run ()
  418.             self._on_authentication_response (d, response)
  419.  
  420.     def _on_authentication_response (self, dialog, response):
  421.         (self._use_user,
  422.          self._use_password) = dialog.get_auth_info ()
  423.         dialog.destroy ()
  424.  
  425.         if (response == gtk.RESPONSE_CANCEL or
  426.             response == gtk.RESPONSE_DELETE_EVENT):
  427.             self._cancel = True
  428.  
  429.         if self._lock:
  430.             self._gui_event.set ()
  431.  
  432. if __name__ == '__main__':
  433.     # Test it out.
  434.     gtk.gdk.threads_init ()
  435.     from timedops import TimedOperation
  436.     set_debugging (True)
  437.     c = TimedOperation (Connection, args=(None,)).run ()
  438.     debugprint ("Connected")
  439.     c._set_lock (True)
  440.     print TimedOperation (c.getFile,
  441.                           args=('/admin/conf/cupsd.conf',
  442.                                 '/dev/stdout')).run ()
  443.